<?php

/*
 * Обработчик изображений.
 * Накладывает фильтры, выводит результат в браузер и записывает в ФС
 */

namespace T4;

class ImageProcessor {

	protected $fileName;
	protected $extension;
	protected $type;
	protected $image;
	protected $mimeType;

	public function __construct($filename) {
		$this->setFileName($filename);
	}

	public function setFileName($filename) {

		$this->fileName = $filename;
		$this->extension = pathinfo($this->fileName, PATHINFO_EXTENSION);

		switch ($this->extension) {
			case 'jpg':
			case 'jpeg':
				$this->type = 'jpeg';
				$this->mimeType = 'image/jpeg';
				break;
			case 'gif':
				$this->type = 'gif';
				$this->mimeType = 'image/gif';
				break;
			case 'bmp':
				$this->type = 'bmp';
				$this->mimeType = 'image/bmp';
				break;
			case 'png':
			default:
				$this->type = 'png';
				$this->mimeType = 'image/png';
				break;
		}

		$this->image = imagecreatefromstring(file_get_contents($this->fileName));
		
	}

	public function applyFilters($filters) {
		$filters = explode('.', $filters);
		foreach ($filters as $filter) {
			preg_match('/(.+?)([0-9-]+)/', $filter, $matches);
			$filterName = 'filter' . strtoupper($matches[1]);
			$filterParams = $matches[2];
			$this->$filterName($filterParams);
		}
	}

	public function output($filename = null) {
		header('Content-type: ' . $this->mimeType);
		$output = 'image' . $this->type;
		$output($this->image, $filename);
	}

	public function __destruct() {
		imagedestroy($this->image);
	}

	/*
	 * ----------------------------------------
	 * Фильтры
	 * ----------------------------------------
	 */

	protected function filterW($width) {

		$oldX = imagesx($this->image);
		$oldY = imagesy($this->image);
		$newX = $width;
		$newY = intval($oldY * $newX / $oldX);

		$newImage = imagecreatetruecolor($newX, $newY);
		imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $newX, $newY, $oldX, $oldY);

		imagedestroy($this->image);
		$this->image = $newImage;
		
	}

}
